import 'dart:io';
import 'dart:async';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/services.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:unique_identifier/unique_identifier.dart';

Future initPlatformState(String appName) async {
  var deviceData = <String, dynamic>{};
  final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();

  try {
    if (Platform.isAndroid) {
      String uid = await UniqueIdentifier.serial ?? '';
      deviceData = _readAndroidBuildData(await deviceInfoPlugin.androidInfo, uid, appName);
    } else if (Platform.isIOS) {
      deviceData = _readIosDeviceInfo(await deviceInfoPlugin.iosInfo, appName);
    }
  } on PlatformException {
    deviceData = <String, dynamic>{'Error:': 'Failed to get platform version.'};
  }
  PackageInfo packageInfo = await PackageInfo.fromPlatform();

  return {...deviceData, "appVersion": packageInfo.version};
}

Map<String, dynamic> _readAndroidBuildData(AndroidDeviceInfo build, String? uid, String appName) {
  return <String, dynamic>{
    'osType': 0,
    'osModel': build.model,
    'osVersion': build.version.release,
    'imei': (uid != null && uid.isNotEmpty) ? (appName.isNotEmpty ? '$appName:$uid' : uid) : build.fingerprint,
    'brand': build.brand ?? '',
  };
}

Map<String, dynamic> _readIosDeviceInfo(IosDeviceInfo data, String appName) {
  return <String, dynamic>{
    'osType': 1,
    'osModel': data.model,
    'osVersion': data.systemVersion,
    'imei': '$appName:${data.identifierForVendor}',
    'brand': 'Apple',
  };
}
